package org.sxf.app.sign.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.lidroid.xutils.util.LogUtils;

import org.sxf.app.sign.constants.Constants;

/**
 * Created by zqc on 16/5/7.
 */
public class ConfigFileUtilsSingleton {
    private static ConfigFileUtilsSingleton ourInstance = new ConfigFileUtilsSingleton();

    public static ConfigFileUtilsSingleton getInstance() {
        return ourInstance;
    }

    private ConfigFileUtilsSingleton() {
    }


    private SharedPreferences sp;

    public void createSP(Context context){
        sp = context.getSharedPreferences(Constants.AID_SK,Context.MODE_PRIVATE);
    }

    public String readConfig(String key){
        try {
            String valueE = sp.getString(key, "");
            String valueEN = sp.getString(key + key, "");
            if ("".equals(valueE) || "".equals(valueEN)){
                return "";
            }

            String valueD = decryptData(valueE);
            String valueDN = decryptData(valueEN);

            if (check(valueD, valueDN)){
                return valueD;
            }

            return "";
        }catch (Exception e){
            return "";
        }
    }

    public void writeConfig(String key, String value){
        try {
            sp.edit().putString(key, encryptData(value)).commit();
            sp.edit().putString(key + key, encryptData(MD5Utils.MD5(value))).commit();
        }catch (Exception e){
            LogUtils.e("wc fail:" + Utility.getStackTrace(e));
        }
    }

    public void clearConfig(String key){
        sp.edit().remove(key).commit();
        sp.edit().remove(key + key).commit();
    }

    private String encryptData(String data){
        String mEncryptData;
        mEncryptData =  PBOCDES.hex(PBOCDES.pboc3DESEncryptForLong(Constants.S, data.getBytes(), true, true));
        LogUtils.d("Encrypt data:" + mEncryptData);
        return mEncryptData;
    }

    private String decryptData(String s){
        byte[] deCode = PBOCDES.pboc3DESDecrypt(Constants.S, PBOCDES.parseBytes(s));
        byte[] len = new byte[]{deCode[0], deCode[1]};
        LogUtils.d(Utility.bytesToHexString(len));
        int lenght = Integer.parseInt(Utility.bytesToHexString(len),16);
        LogUtils.d(lenght + "");
        byte[] value = new byte[lenght];
        System.arraycopy(deCode, 2, value, 0, lenght);
        String data = new String(value);
        return data;
    }

    private boolean check(String value, String md5){
        try {
            String vMD5 = MD5Utils.MD5(value);
            if (md5.equalsIgnoreCase(vMD5)){
                return true;
            }else {
                return false;
            }
        }catch (Exception e){
            return false;
        }

    }
}
